package util;

import com.intellij.database.psi.DbNamespaceImpl;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.psi.PsiElement;

import java.util.stream.Stream;

public class PluginExistsUtils {
    private static volatile Boolean existsDatabaseTools = null;

    public static void existsDbTools(AnActionEvent e) {
        Boolean visible = null;
        PsiElement[] psiElements = e.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
        if (psiElements == null || psiElements.length == 0) {
            visible = false;
        }
        boolean existsDbTools = PluginExistsUtils.existsDbTools();
        if (!existsDbTools) {
            visible = false;
        }
        if (visible == null) {
            if (!Stream.of(psiElements).allMatch(item -> CheckMatch.checkAssignableFrom(item.getClass()))) {
                visible = false;
            }
        }
        if (visible != null) {
            e.getPresentation().setEnabledAndVisible(visible);
        }
    }

    private static boolean existsDbTools() {
        if (existsDatabaseTools == null) {
            synchronized (PluginExistsUtils.class) {
                if (existsDatabaseTools == null) {
                    try {
                        Class.forName("com.intellij.database.psi.DbTable");
                        existsDatabaseTools = true;
                    } catch (ClassNotFoundException ex) {
                        existsDatabaseTools = false;
                    }
                }
            }
        }
        return existsDatabaseTools;
    }

    private static class CheckMatch {
        public static boolean checkAssignableFrom(Class<? extends PsiElement> aClass) {
            try {
                return DbNamespaceImpl.class.isAssignableFrom(aClass);
            } catch (Exception e) {
                return false;
            }
        }
    }
}
